<?php

declare(strict_types=1);

namespace app\common\model;

use think\Model;
use think\facade\Db;
use think\model\concern\SoftDelete;


class Menu extends Model
{
    use SoftDelete;  // 使用软删除trait
    protected $pk = 'menu_id';
    protected $name = 'menu';

    // 自动时间戳类型
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 定义软删除字段
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = null;

    /**
     * 检查菜单是否被角色使用
     * @param int $menuId
     * @return bool
     */
    public function isMenuUsed(int $menuId): bool
    {
        return Db::name('role_menu')
            ->where('menu_id', $menuId)
            ->count() > 0;
    }

    /**
     * 获取路由信息
     * @param array $roles 角色列表
     * @return array
     */
    public function getRouters(array $roles): array
    {
        // 如果是超级管理员，返回所有菜单
        if (in_array('super_admin', $roles)) {
            $menus = $this->where('status', 1)
                ->where('type', 1)
                ->order('sort', 'asc')
                ->select()
                ->toArray();
        } else {
            // 获取角色对应的角色ID
            $roleIds = Db::name('role')
                ->whereIn('code', $roles)
                ->where('status', 1)
                ->column('role_id');

            if (empty($roleIds)) {
                return [];
            }

            // 获取角色对应的按钮权限菜单ID
            $buttonMenuIds = Db::name('role_menu')
                ->alias('rm')
                ->whereIn('rm.role_id', $roleIds)
                ->join('menu m', 'm.menu_id = rm.menu_id')
                ->where('m.type', 2) // 只获取按钮类型的权限
                ->column('m.menu_id');

            if (empty($buttonMenuIds)) {
                return [];
            }

            // 获取这些按钮对应的父级菜单ID
            $parentMenus = $this->whereIn('menu_id', $buttonMenuIds)
                ->column('parent_id');

            // 获取父级菜单的父级菜单ID（处理三级菜单的情况）
            $grandParentMenus = $this->whereIn('menu_id', $parentMenus)
                ->where('parent_id', '<>', 0)
                ->column('parent_id');

            // 合并所有需要显示的菜单ID
            $allMenuIds = array_unique(array_merge($grandParentMenus, $parentMenus));

            // 获取完整的菜单树
            $menus = $this->where('status', 1)
                ->where('type', 1)
                ->whereIn('menu_id', $allMenuIds)
                ->order('sort', 'asc')
                ->select()
                ->toArray();
        }

        // 构建树形结构
        return $this->buildRouterTree($menus);
    }

    /**
     * 构建路由树
     * @param array $menus
     * @param int $parentId
     * @return array
     */
    protected function buildRouterTree(array $menus, int $parentId = 0): array
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $route = [
                    'name' => $menu['name'],
                    'path' => $menu['path'],
                    'component' => $menu['component'],
                    'meta' => [
                        'title' => $menu['title'],
                        'icon' => $menu['icon'],
                        'isCustomSvg' => (bool)$menu['is_custom_svg'],
                        'noKeepAlive' => (bool)$menu['no_keep_alive'],
                        'hidden' => (bool)$menu['hidden']
                    ]
                ];

                // 处理重定向
                if (!empty($menu['redirect'])) {
                    $route['redirect'] = $menu['redirect'];
                }

                // 递归获取子菜单
                $children = $this->buildRouterTree($menus, $menu['menu_id']);
                if (!empty($children)) {
                    $route['children'] = $children;
                }

                $tree[] = $route;
            }
        }
        return $tree;
    }
}
